package com.example.mybatis.utils.validator;


import com.example.mybatis.utils.exception.MyException;


import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * 数据校验工具类
 */
public class DataValidator {
    public static void validator(Object obj, Class<?>... groups){
        //创建校验对象
        Validator validator=Validation.buildDefaultValidatorFactory().getValidator();
        //调用校验方法
        Set<ConstraintViolation<Object>> resultSet=validator.validate(obj,groups);
        if(!resultSet.isEmpty()){
            String message=resultSet.iterator().next().getMessage();
            System.out.println(message);
            //抛出自定义java逻辑异常类对象
            throw new MyException("error", message);
        }


    }


}
